package com.len.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.len.base.BaseController;
import com.len.core.annotation.Log;
import com.len.core.annotation.Log.LOG_TYPE;
import com.len.entity.TProductDemand;
import com.len.entity.TProductNotice;
import com.len.entity.TTaskDetails;
import com.len.exception.MyException;
import com.len.service.ProductDemandService;
import com.len.service.ProductService;
import com.len.service.TaskDetailsService;
import com.len.util.BeanUtil;
import com.len.util.JsonUtil;
import com.len.util.ReType;
import com.len.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("product")
@Api(value = "生产通知单",description="生产通知单业务处理")
public class ProductControlller  extends BaseController {
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductDemandService productDemandService;
    @Autowired
    private TaskDetailsService taskDetailsService;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Log(desc = "更新生产通知单", type = LOG_TYPE.ADD)
    @PostMapping("/updateProduct")
    @ResponseBody
    public JsonUtil updateProduct(@RequestBody JSONObject tProductNotice) {

        List<TProductDemand> productDemands = JSON.parseArray(tProductNotice.getString("taskDetails"),TProductDemand.class);
        tProductNotice.remove("taskDetails");
        TProductNotice productNotice = JSONObject.toJavaObject(tProductNotice,TProductNotice.class);

        TProductNotice oldproduct = productService.selectByPrimaryKey(productNotice.getId());
        BeanUtil.copyNotNullBean(productNotice, oldproduct);
        productService.updateByPrimaryKeySelective(oldproduct);

        for(int i =0;i< productDemands.size();i++){
            TProductDemand oldTaskDetail = productDemandService.selectByPrimaryKey(productDemands.get(i).getId());
            if(null!=oldTaskDetail) {
                BeanUtil.copyNotNullBean(productDemands.get(i), oldTaskDetail);
                productDemandService.updateByPrimaryKeySelective(oldTaskDetail);
            }else {
                productDemandService.insert(productDemands.get(i));
            }
        }
        return JsonUtil.sucess("保存成功");
    }
    @Autowired
    UploadUtil uploadUtil;
    @RequestMapping("/showProductDemand")
    @ResponseBody
    public ReType showDemand(String id, Model model, boolean detail) {
        ReType reType = new ReType();
        List<TProductDemand> taskDetails = productDemandService.selectAllByOrderNo(id);
        reType.setData(taskDetails);
        return reType;
    }
    /**
     * 头像上传 目前首先相对路径
     */
    @PostMapping(value = "upload")
    @ResponseBody
    public JsonUtil imgUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file,
                              ModelMap model) {
        String fileName = uploadUtil.upload(file);
        JsonUtil j = new JsonUtil();
        j.setMsg(fileName);
        return j;
    }

    @Log(desc = "删除生产通知单", type = LOG_TYPE.DEL)
    @PostMapping("/delProduct")
    @ResponseBody
    public JsonUtil del(String id) {
        try {
            TProductNotice tProductNotice = productService.selectByPrimaryKey(id);
            taskDetailsService.delAllByOrderNo(tProductNotice.getOrderNo());
            return productService.del(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setMsg("删除失败");
        return jsonUtil;
    }

    @GetMapping(value = "showAddProduct")
    public String goAddUser(Model model) {
//        List<Checkbox> checkboxList = productService.getUserRoleByJson(null);
//        model.addAttribute("boxJson", checkboxList);
        return "/act/product/add-product";
    }

    @Log(desc = "添加生产通知单", type = LOG_TYPE.UPDATE)
    @ApiOperation(value = "/addProduct", httpMethod = "POST", notes = "添加生产通知单")
    @PostMapping("/addProduct")
    @ResponseBody
    public JsonUtil addMenu( TProductNotice tProductNotice , Model model) {
        JsonUtil jsonUtil = new JsonUtil();
        jsonUtil.setFlag(false);
        if (tProductNotice == null) {
            jsonUtil.setMsg("获取数据失败");
            return jsonUtil;
        }
        try {
            tProductNotice.setIspay("否");
            productService.insertSelective(tProductNotice);
            List<TProductDemand> taskDetails = tProductNotice.getTaskDetails();
            for (TProductDemand ta : taskDetails
                    ) {
                if(StringUtils.isEmpty(ta.getSample())){
                    continue;
                }
                ta.setOrderNo(tProductNotice.getOrderNo());
                productDemandService.insertSelective(ta);
            }
//            taskDetailsService.insertList(tProductNotice.getTaskDetails());
            jsonUtil.setMsg("添加成功");
        } catch (MyException e) {
            e.printStackTrace();
            jsonUtil.setMsg("添加失败");
        }
        return jsonUtil;
    }

    @GetMapping(value = "/showProduct")
    @RequiresPermissions("product:show")
    public String showUser(Model model) {
        return "/act/product/productList";
    }
    @RequestMapping("/showTaskDetails")
    @ResponseBody
    public ReType showTaskDetails(String id, Model model, boolean detail) {
        ReType reType = new ReType();
        //根据orderNo查询所有的子表
        List<TProductDemand> taskDetails = productDemandService.selectAllByOrderNo(id);
        reType.setData(taskDetails);
        return reType;
    }
    @RequestMapping("/showProductList")
    @ResponseBody
    @RequiresPermissions("product:show")
    public ReType showUser(Model model, TProductNotice tProductNotice, String page, String limit) {
        ReType reType = productService.show(tProductNotice, Integer.valueOf(page), Integer.valueOf(limit));
        return productService.show(tProductNotice, Integer.valueOf(page), Integer.valueOf(limit));
    }

    @GetMapping(value = "detailProduct")
    public String goUpdateUser(String id, Model model, boolean detail) {
        if (StringUtils.isNotEmpty(id)) {
            //用户-角色
//            List<Checkbox> checkboxList = productService.getUserRoleByJson(id);
            TProductNotice tProductNotice = productService.selectByPrimaryKey(id);
            List<TTaskDetails> taskDetails = taskDetailsService.selectAllByOrderNo(tProductNotice.getOrderNo());
            model.addAttribute("productNotice", tProductNotice);
            model.addAttribute("taskDetail", taskDetails);
//            model.addAttribute("boxJson", checkboxList);
        }
        model.addAttribute("detail", detail);
        return "/act/product/update-product";
    }

    @PostMapping("/download")
    public void UserExcelDownloads(HttpServletResponse response,String id)throws IOException {

        TProductNotice tProductNotice = productService.selectByPrimaryKey(id);
        List<TProductDemand> taskDetails = productDemandService.selectAllByOrderNo(tProductNotice.getOrderNo());
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("生产通知表");
        sheet.setColumnWidth(0, 40 * 256);//设置列的宽度
//        List<ReportDTO> UserExcelDownloads = reportService.findAllByPatientId(reportId);
        String fileName = "生成通知单" + ".xls";
        HSSFCellStyle style = workbook.createCellStyle();

        style.setAlignment(HorizontalAlignment.CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        sheet.setColumnWidth(0, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(1, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(2, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(3, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(4, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(5, 40 * 256);//设置列的宽度
        sheet.setColumnWidth(6, 20 * 256);//设置列的宽度
        sheet.setColumnWidth(7, 20 * 256);//设置列的宽度
        //合并单元格
        //第一行
        Row row0 = sheet.createRow(0);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
        row0.createCell(0).setCellValue("山东创联三维科技有限公司");
        row0.getCell(0).setCellStyle(style);
        sheet.getRow(0).setHeight((short) 1000);
        //第2行
        Row row1 = sheet.createRow(1);
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 7));
        row1.createCell(1).setCellValue("生  产  通  知  单");
        row1.getCell(1).setCellStyle(style);
        sheet.getRow(1).setHeight((short) 700);
        //第3行
        Row row2 = sheet.createRow(2);
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 5));
        row2.createCell(0).setCellValue("订单编号");
        row2.createCell(1).setCellValue(tProductNotice.getOrderNo());
        row2.createCell(6).setCellValue("通知单下发时间");
        if(null!=tProductNotice.getNoticeTime()) {
            row2.createCell(7).setCellValue(sdf.format(tProductNotice.getNoticeTime()));
        }else {
            row2.createCell(7).setCellValue(sdf.format(new Date()));
        }
        row2.getCell(0).setCellStyle(style);
        sheet.getRow(0).setHeight((short) 500);
        //第4行
        Row row3 = sheet.createRow(3);
        sheet.addMergedRegion(new CellRangeAddress(3, 3, 3, 5));
        row3.createCell(0).setCellValue("销售");
        row3.createCell(1).setCellValue(tProductNotice.getSaleName());
        row3.createCell(2).setCellValue("收货地址");
        row3.createCell(3).setCellValue(tProductNotice.getCustomerAddress());
        row3.createCell(6).setCellValue("交货日期");
        row3.createCell(7).setCellValue(sdf.format(tProductNotice.getDeliveryDate()));
        row3.getCell(0).setCellStyle(style);
        sheet.getRow(0).setHeight((short) 500);
        //第5-8行
        Row row4 = sheet.createRow(4);
        Row row5 = sheet.createRow(5);
        Row row6 = sheet.createRow(6);
        Row row7 = sheet.createRow(7);
        row5.createCell(0).setCellStyle(style);
        sheet.getRow(4).setHeight((short) 500);
        row6.createCell(0).setCellStyle(style);
        sheet.getRow(5).setHeight((short) 500);
        row7.createCell(0).setCellStyle(style);
        sheet.getRow(6).setHeight((short) 500);
        row4.createCell(0).setCellStyle(style);
        sheet.getRow(7).setHeight((short) 500);
        sheet.addMergedRegion(new CellRangeAddress(4, 7, 0, 0));
        sheet.addMergedRegion(new CellRangeAddress(4, 4, 6, 7));
        sheet.addMergedRegion(new CellRangeAddress(5, 5, 6, 7));
        sheet.addMergedRegion(new CellRangeAddress(6, 6, 6, 7));
        sheet.addMergedRegion(new CellRangeAddress(7, 7, 6, 7));
        row4.createCell(0).setCellValue("任务详情");
        row4.createCell(1).setCellValue("样件名称");
        row4.createCell(2).setCellValue("材料");
        row4.createCell(3).setCellValue("设计");
        row4.createCell(4).setCellValue("数量");
        row4.createCell(5).setCellValue("工艺");
        row4.createCell(6).setCellValue("处理");

        for (int i = 0; i < taskDetails.size(); i++) {
            TProductDemand taskDetails1 = taskDetails.get(i);
            Row rowi = sheet.getRow(i + 5);
            rowi.createCell(1).setCellValue(taskDetails1.getSample());
            rowi.createCell(2).setCellValue(taskDetails1.getMaterial());
            rowi.createCell(3).setCellValue(taskDetails1.getDesign());
            rowi.createCell(4).setCellValue(taskDetails1.getNumber());
            rowi.createCell(5).setCellValue(taskDetails1.getTechnology());
            rowi.createCell(6).setCellValue(taskDetails1.getHandle());
        }
        //第9行
        Row row8 = sheet.createRow(8);
        sheet.addMergedRegion(new CellRangeAddress(8, 8, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(8, 8, 3, 4));
        row8.createCell(0).setCellValue("部门签字");
        row8.createCell(1).setCellValue("结构/支撑设计");
//        row8.createCell(2).setCellValue("材料");
        row8.createCell(3).setCellValue("设备");
//        row8.createCell(4).setCellValue("数量");
        row8.createCell(5).setCellValue("后处理");
        row8.createCell(6).setCellValue("质检");
        row8.createCell(7).setCellValue("发货人");
        row8.getCell(0).setCellStyle(style);
        sheet.getRow(8).setHeight((short) 500);
        //第10行
        Row row9 = sheet.createRow(9);
        sheet.addMergedRegion(new CellRangeAddress(9, 9, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(9, 9, 3, 4));
        row9.createCell(0).setCellValue("确认签字");
        row9.createCell(1);
//        row8.createCell(2).setCellValue("材料");
        row9.createCell(3);
//        row8.createCell(4).setCellValue("数量");
        row9.createCell(5);
        row9.createCell(6);
        row9.createCell(7);
        row9.getCell(0).setCellStyle(style);
        row9.setRowStyle(style);
        sheet.getRow(9).setHeight((short) 500);
        //第11行
        Row row10 = sheet.createRow(10);
        sheet.addMergedRegion(new CellRangeAddress(10, 10, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(10, 10, 3, 4));
        row10.createCell(0).setCellValue("起止时间");
        row10.createCell(1);
//        row8.createCell(2).setCellValue("材料");
        row10.createCell(3);
//        row8.createCell(4).setCellValue("数量");
        row10.createCell(5);
        row10.createCell(6);
        row10.createCell(7);
        row10.getCell(0).setCellStyle(style);
        sheet.getRow(10).setHeight((short) 500);
        //第12行
        Row row11 = sheet.createRow(11);
        sheet.addMergedRegion(new CellRangeAddress(11, 11, 1, 7));
        row11.createCell(0).setCellValue("客户反馈");
        row11.createCell(1).setCellValue(tProductNotice.getFeedback());

        row11.getCell(0).setCellStyle(style);
        row11.getCell(1).setCellStyle(style);
        sheet.getRow(11).setHeight((short) 1000);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");

        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/trans")
    @ResponseBody
//    @RequiresPermissions("product:show")
    public ReType trans(String id) {
        TProductNotice tProductNotice = productService.selectByPrimaryKey(id);
        return  null;
    }


}
